package apps.softtech.fastmarket;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.internal.widget.ActivityChooserModel.ActivitySorter;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import apps.sofftech.twitter.ActivityLoginTwitter;
import apps.softtech.Utility.ApplicationConstants;
import apps.softtech.Utility.ConnectionDetector;
import apps.softtech.Utility.DownloadImage;
import apps.softtech.Utility.HttpRequest;
import apps.softtech.Utility.ImageHelper;
import apps.softtech.fastmarket.model.DatabaseHandler;
import apps.softtech.fastmarket.model.UserInfo;
import apps.softtech.gplus.SignInGoogle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.maps.model.UrlTileProvider;

public class ActivityRegister extends Activity {

	/*
	 * bien dung de login vao twitter
	 */
	private static String CONSUMER_KEY = "S96q8FRvUoz8o7uLVYJiF12jE";
	private static String CONSUMER_SECRET = "bVDTGkK7P9ThKx8X5MpjG7CgsCAtsmWYRFN1iIylvIsYdne1IT";
	Twitter twitter;
	RequestToken requestToken = null;
	AccessToken accessToken;
	private String oauth_url, oauth_verifier;
	WebView web;
	Dialog auth_twitter_dialog;
	ProgressDialog progress;

	protected static final int REQUEST_CODE_FB = 1;
	protected static final int REQUEST_CODE_TWITTER = 2;
	protected static final int REQUEST_CODE_GOOGLE = 3;
	protected static final int SELECT_PICTURE = 4;

	public static final int RESULT__FB = 11;
	public static final int RESULT_TWITTER = 22;
	public static final int RESULT_GOOGLE = 33;

	public static final String EXTRA_MESSAGE = "message";
	public static final String PROPERTY_REG_ID = "registration_id";
	private static final String PROPERTY_APP_VERSION = "appVersion";
	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
	private static final String URL_REGISTER = ApplicationConstants.BASE_URL + "users/register/1";
	private static final String URL_UPLOAD_AVATAR = ApplicationConstants.BASE_URL +  "upload/do_upload_avatar";
	public static final String BROADCAST_ACTION_TWITTER = "apps.sofftech.fastmarket.twitter";

	GoogleCloudMessaging gcm;
	AtomicInteger msgId = new AtomicInteger();
	SharedPreferences prefs;
	String regid;
	private static final String TAG = "ActivityRegister";

	private EditText edtUsername, edtPassword, edtEmail, edtPhonenumber,
			edtAddress, edtSecretAnswer;
	private Button btnRegister;
	private TextView tvAlert;
	private Spinner spinerScret;
	private ImageView imgFb, imgTwitter, imgGoogle, imgAvatar;

	// save position of secretQuesttion was selected
	private int postionQuestion = 0;

	private Context mContext;

	private String mUserId, mUsername, mPassword, mEmail, mPhonenumber,
			mAddress, mSecretAnswer, mAvatarUrl;

	// save path of image avatar when user register = twitter or fb or gg
	private String mSelectedImagePath;
	// bitmap of image avatar
	public static Bitmap mBitmap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_registration);
		mContext = this;
		twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
		init();
		getEvent();
	}

	private void init() {
		edtUsername = (EditText) findViewById(R.id.edtUsername);
		edtPassword = (EditText) findViewById(R.id.edtPassword);
		edtEmail = (EditText) findViewById(R.id.edtEmail);
		edtPhonenumber = (EditText) findViewById(R.id.edtPhoneNumber);
		edtAddress = (EditText) findViewById(R.id.edtAddress);
		btnRegister = (Button) findViewById(R.id.btnRegister);
		tvAlert = (TextView) findViewById(R.id.tvAlert);
		spinerScret = (Spinner) findViewById(R.id.spinner1);
		edtSecretAnswer = (EditText) findViewById(R.id.edtSecretPassword);

		imgFb = (ImageView) findViewById(R.id.imgFb);
		imgTwitter = (ImageView) findViewById(R.id.imgTwitter);
		imgGoogle = (ImageView) findViewById(R.id.imgGooglePlus);
		imgAvatar = (ImageView) findViewById(R.id.imgAvatar);

		String arrSecretQuestion[] = { "TrÆ°á»�ng THPT cá»§a báº¡n lÃ  gÃ¬?",
				"Ä�á»™i bÃ³ng yÃªu thÃ­ch cá»§a báº¡n lÃ  gÃ¬?",
				"MÃ´n thá»ƒ thao yÃªu thÃ­ch cá»§a báº¡n lÃ  gÃ¬?",
				"MÃ´n há»�c báº¡n ghÃ©t nháº¥t lÃ  gÃ¬?" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext,
				android.R.layout.simple_spinner_item, arrSecretQuestion);
		adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		spinerScret.setAdapter(adapter);
	}

	private void getEvent() {
		final DatabaseHandler db = new DatabaseHandler(mContext);

		// set event for Spinner
		spinerScret.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				postionQuestion = position;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

		imgAvatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(
						Intent.createChooser(intent, "Select Picture"),
						SELECT_PICTURE);
			}
		});

		imgFb.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// do something
			}
		});

		imgTwitter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent(mContext,
				// ActivityLoginTwitter.class);
				// startActivityForResult(intent, REQUEST_CODE_TWITTER);
				new TokenGet().execute();

			}
		});

		imgGoogle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, SignInGoogle.class);
				startActivityForResult(intent, REQUEST_CODE_GOOGLE);
			}
		});
		btnRegister.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				saveUserInfo();
				ConnectionDetector connectionDetector = new ConnectionDetector(
						mContext);
				if (connectionDetector.isConnectingToInternet()) {
					if (checkValidation()) {
						getBitmapImageView();
						register(ApplicationConstants.RED_ID, mUsername,
								mPassword, mEmail, mPhonenumber, mAddress,
								postionQuestion, mSecretAnswer);
					}
				} else {
					Toast.makeText(mContext, "Netword not available",
							Toast.LENGTH_SHORT).show();

				}
			}
		});
	}

	/**
	 * Register user
	 * 
	 * @param gcmId
	 * @param username
	 * @param password
	 * @param email
	 * @param phoneNumber
	 * @param address
	 */

	@SuppressWarnings({ "unused", "unchecked" })
	private void register(String gcmId, String username, String password,
			String email, String phoneNumber, String address,
			int secretQuestion, String answer) {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		JSONObject jsonOject = new JSONObject();
		try {
			jsonOject.put(UserInfo.GCMID, gcmId);
			jsonOject.put(UserInfo.USERNAME, username);
			jsonOject.put(UserInfo.PASSWORD, password);
			jsonOject.put(UserInfo.EMAIL, email);
			jsonOject.put(UserInfo.PHONENUMBER, phoneNumber);
			jsonOject.put(UserInfo.ADDRESS, address);
			jsonOject.put("st_SecretQuestion", secretQuestion);
			jsonOject.put("st_SecretAnswer", answer);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.add(new BasicNameValuePair("data", jsonOject.toString()));

		new AsyncTask<List<NameValuePair>, Void, String>() {

			protected void onPreExecute() {
				progress = new ProgressDialog(mContext);
				progress.setMessage("Registating ...");
				progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				progress.setIndeterminate(true);
				progress.show();
			};

			@Override
			protected String doInBackground(List<NameValuePair>... params) {
				HttpRequest request = new HttpRequest();
				String result = request.makeServiceCall(URL_REGISTER,
						HttpRequest.POST, params[0]);
				return result;

			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				progress.hide();

				try {
					JSONObject json = new JSONObject(result);
					if (json.getString("success") != null) {
						String check = json.getString("success");
						if (Integer.parseInt(check) == 1) {
							Toast.makeText(mContext, "Register complete",
									Toast.LENGTH_SHORT).show();
							/*
							 * save userinfo regiter success into data
							 */
							insertUserinfo(json.getJSONObject("data"));

							/*
							 * if user chose image lam avatar thi save image do
							 * vao app
							 */
							if (mBitmap != null) {
								saveImageInApp(mBitmap, mUserId);
							}

							/*
							 * Register thanh cong thi chuyen qua giao dien
							 * login
							 */
							Intent intent = new Intent(mContext,
									ActivityLogin.class);
							intent.putExtra(UserInfo.USERNAME, mUsername);
							startActivity(intent);
							ActivityRegister.this.finish();

						} else {
							if (Integer.parseInt(check) == 0) {
								Toast.makeText(mContext,
										"Register khong thanh cong",
										Toast.LENGTH_SHORT).show();
							}
						}
					} else {
						Toast.makeText(mContext, "Register no complete",
								Toast.LENGTH_SHORT).show();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute(params);

	}

	public Boolean checkValidation() {
		if ((checkUsername() == 1) && (checkPassword() == 1)
				&& (checkEmail() == 1) && (checkPhonenumber() == 1)
				&& (checkSecretAnswer() == 1)) {
			Log.i(TAG, "validation ok!");
			return true;
		}
		Log.i(TAG, "input invalid!");
		return false;
	}

	/**
	 * @author MUI check valid of username
	 * @return 1 if valid, 0 if invalid
	 */
	private int checkUsername() {
		mUsername = edtUsername.getText().toString();
		DatabaseHandler db = new DatabaseHandler(mContext);
		List<UserInfo> listUser = new ArrayList<UserInfo>();
		if (mUsername.equals(null) || mUsername.equals("")) {
			tvAlert.setVisibility(View.VISIBLE);
			tvAlert.setText(getResources().getString(
					R.string.please_enter_your_username));
			return 0;
		}
		if (mUsername.contains("admin") || mUsername.contains("FastMarket")) {
			tvAlert.setVisibility(View.VISIBLE);
			tvAlert.setText(getResources().getString(R.string.username_invalid));
			return 0;
		}
		if (!isAlphaNumberic(mUsername)) {
			tvAlert.setVisibility(View.VISIBLE);
			tvAlert.setText(getResources().getString(R.string.username_invalid));
			return 0;
		}
		if (mUsername.length() >= 99) {
			Toast.makeText(mContext,
					getResources().getString(R.string.username_invalid),
					Toast.LENGTH_LONG).show();
			return 0;
		}
		// listUser = db.getUserInfo(null, UserInfo.USERNAME + " = " +
		// mUsername,
		// null, null, null);
		//
		// if (listUser.size() > 0) {
		// tvAlert.setText(getResources().getString(R.string.username_exist));
		// tvAlert.setVisibility(View.VISIBLE);
		// return 0;
		// }
		return 1;
	}

	/**
	 * check if String co ky tu dac biet return false
	 * 
	 * @param st
	 * @return true neu string chi chua so va chu cai
	 */
	private Boolean isAlphaNumberic(String st) {
		String pattern = "^[a-zA-Z0-9]*$";
		if (st.matches(pattern)) {
			return true;
		}
		return false;
	}

	/**
	 * @author MUI check valid of password
	 * @return 1 if valid, 0 if invalid
	 */
	private int checkPassword() {
		mPassword = edtPassword.getText().toString();
		if (mPassword.equals(null) || mPassword.equals("")
				|| mPassword.length() >= 100 || mPassword.length() <= 6) {
			Toast.makeText(mContext,
					getResources().getString(R.string.password_invalid),
					Toast.LENGTH_LONG).show();
			return 0;
		}
		return 1;
	}

	/**
	 * @author MUI check valid of Email
	 * 
	 * @return 1 if valid, 0 if invalid
	 */
	private int checkEmail() {
		mEmail = edtEmail.getText().toString();
		if (mEmail.equals(null) || mEmail.equals("") || mEmail.length() >= 100) {
			Toast.makeText(mContext,
					getResources().getString(R.string.email_invalid),
					Toast.LENGTH_LONG).show();
			return 0;
		}
		if (!emailValidator(mEmail)) {
			Toast.makeText(mContext,
					getResources().getString(R.string.email_invalid),
					Toast.LENGTH_LONG).show();
			return 0;
		}
		return 1;
	}

	/**
	 * check valid of email
	 * 
	 * @param st
	 * @return true if valid, false if invalid
	 */
	private Boolean emailValidator(String st) {
		String email_pattern = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
				+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		Pattern pattern;
		Matcher matcher;
		pattern = Pattern.compile(email_pattern);
		matcher = pattern.matcher(st);
		return matcher.matches();
	}

	/**
	 * @author MUI check valid of phone number
	 * 
	 * @return 1 if valid, 0 if invalid
	 */
	private int checkPhonenumber() {
		mPhonenumber = edtPhonenumber.getText().toString();
		if (mPhonenumber.equals(null) || mPhonenumber.equals("")
				|| mPhonenumber.length() >= 100) {
			Toast.makeText(mContext,
					getResources().getString(R.string.phonenumer_invalid),
					Toast.LENGTH_LONG).show();
			return 0;
		}
		return 1;
	}

	/**
	 * check SecretAnswer
	 * 
	 * @return
	 */
	private int checkSecretAnswer() {
		mSecretAnswer = edtSecretAnswer.getText().toString();
		if (mSecretAnswer.equals("") || mSecretAnswer.equals(null)) {
			Toast.makeText(mContext, "ChÆ°a nháº­p cÃ¢u há»�i báº£o máº­t",
					Toast.LENGTH_LONG).show();
			return 0;
		}
		return 1;
	}

	private void saveUserInfo() {
		mUsername = edtUsername.getText().toString();
		mPassword = edtPassword.getText().toString();
		mEmail = edtEmail.getText().toString();
		mPhonenumber = edtPhonenumber.getText().toString();
		mAddress = edtAddress.getText().toString();
		mSecretAnswer = edtSecretAnswer.getText().toString();
	}

	/**
	 * @author MUI insert UserInfo into table UserInfo when receive response
	 *         success from server
	 * @param json
	 */
	private void insertUserinfo(JSONObject json) {
		try {
			mUserId = json.getString(UserInfo.USERID);
			String userName = json.getString(UserInfo.USERNAME);
			String email = json.getString(UserInfo.PHONENUMBER);
			String phoneNumber = json.getString(UserInfo.PHONENUMBER);
			String address = json.getString(UserInfo.PHONENUMBER);
			String createdDate = json.getString(UserInfo.PHONENUMBER);
			int userPermissionId = 0;
			if (json.getString(UserInfo.USER_PERMISSION_ID) != null) {
				userPermissionId = Integer.parseInt(json
						.getString(UserInfo.USER_PERMISSION_ID));
			}
			float rate = 0;
			if (json.getString(UserInfo.RATE) != null) {
				rate = Float.parseFloat(json.getString(UserInfo.RATE));
			}

			UserInfo userInfo = new UserInfo(userName, "", email, phoneNumber,
					address, createdDate, userPermissionId, rate, 0.0, 0.0,
					null, 1);
			DatabaseHandler db = new DatabaseHandler(mContext);
			db.insertUserInfo(userInfo);

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	/**
	 * get Bitmap of image in imageView
	 */
	private void getBitmapImageView() {
		Drawable d = imgAvatar.getDrawable();
		mBitmap = ((BitmapDrawable) d).getBitmap();
	}

	@SuppressWarnings("unchecked")
	private void uploadAvatarToServer() {

		getBitmapImageView();

		String fileName = "avatar" + mUsername;
		progress = new ProgressDialog(mContext);
		progress.setMessage("Uploading avatar ...");
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setIndeterminate(true);
		progress.show();
		new Thread(new Runnable() {

			@Override
			public void run() {
				uploadFile(edtUsername.getText().toString());
			}
		}).start();
	}

	int serverResponseCode = 0;

	private int uploadFile(String fileName) {

		HttpURLConnection conn = null;
		DataOutputStream dos = null;
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1 * 1024 * 1024;
		File sourceFile = new File(fileName);

		if (!sourceFile.isFile()) {

			progress.dismiss();

			Log.e("uploadFile", "Source File not exist :" + mSelectedImagePath);
			return 0;

		} else {
			try {

				// open a URL connection to the Servlet
				FileInputStream fileInputStream = new FileInputStream(
						sourceFile);
				URL url = new URL(URL_UPLOAD_AVATAR);

				// Open a HTTP connection to the URL
				conn = (HttpURLConnection) url.openConnection();
				conn.setDoInput(true); // Allow Inputs
				conn.setDoOutput(true); // Allow Outputs
				conn.setUseCaches(false); // Don't use a Cached Copy
				conn.setRequestMethod("POST");
				conn.setRequestProperty("Connection", "Keep-Alive");
				conn.setRequestProperty("ENCTYPE", "multipart/form-data");
				conn.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundary);
				conn.setRequestProperty("userfile", fileName);
				conn.setRequestProperty(UserInfo.USERID, "");

				dos = new DataOutputStream(conn.getOutputStream());

				dos.writeBytes(twoHyphens + boundary + lineEnd);
				dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
						+ fileName + "\"" + lineEnd);

				dos.writeBytes(lineEnd);

				// create a buffer of maximum size
				bytesAvailable = fileInputStream.available();

				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				buffer = new byte[bufferSize];

				// read file and write it into form...
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);

				while (bytesRead > 0) {

					dos.write(buffer, 0, bufferSize);
					bytesAvailable = fileInputStream.available();
					bufferSize = Math.min(bytesAvailable, maxBufferSize);
					bytesRead = fileInputStream.read(buffer, 0, bufferSize);

				}

				// send multipart form data necesssary after file data...
				dos.writeBytes(lineEnd);
				dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

				// Responses from the server (code and message)
				serverResponseCode = conn.getResponseCode();
				String serverResponseMessage = conn.getResponseMessage();

				Log.i("uploadFile", "HTTP Response is : "
						+ serverResponseMessage + ": " + serverResponseCode);

				// why = 200
				if (serverResponseCode == 200) {

					runOnUiThread(new Runnable() {
						public void run() {
							String msg = "File Upload Completed";
							Toast.makeText(getApplicationContext(), msg,
									Toast.LENGTH_SHORT).toString();
						}
					});
				}

				// close the streams //
				fileInputStream.close();
				dos.flush();
				dos.close();

			} catch (MalformedURLException ex) {

				// dialog.dismiss();
				ex.printStackTrace();

				runOnUiThread(new Runnable() {
					public void run() {
						// messageText
						// .setText("MalformedURLException Exception : check script url.");
						Toast.makeText(getApplicationContext(),
								"MalformedURLException", Toast.LENGTH_SHORT)
								.show();
					}
				});

				Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
			} catch (Exception e) {

				// dialog.dismiss();
				e.printStackTrace();

				runOnUiThread(new Runnable() {
					public void run() {
						// messageText.setText("Got Exception : see logcat ");
						Toast.makeText(getApplicationContext(),
								"Got Exception : see logcat ",
								Toast.LENGTH_SHORT).show();
					}
				});
				Log.e("Upload file to server Exception",
						"Exception : " + e.getMessage(), e);
			}
			progress.dismiss();
			return serverResponseCode;

		} // End else block

	}

	/**
	 * save image avatar in app
	 * 
	 * @param bitmap
	 * @param name
	 */
	private void saveImageInApp(Bitmap bitmap, String name) {
		name = "avatar" + name;
		DownloadImage dowloadImage = new DownloadImage(mContext, imgAvatar);
		mSelectedImagePath = ImageHelper.saveImageToApp(mContext, bitmap, name);
		Log.i(TAG, "SAVE IMAGE path: " + mSelectedImagePath);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_GOOGLE) {

			if (resultCode == RESULT_GOOGLE) {
				mAvatarUrl = data.getStringExtra("avatar");
				edtEmail.setText(data.getStringExtra(UserInfo.EMAIL));
				edtUsername.setText(data.getStringExtra(UserInfo.USERNAME));
				DownloadImage dowloadImage = new DownloadImage(mContext,
						imgAvatar);
				dowloadImage.execute(mAvatarUrl);
				// mBitmap = dowloadImage.getBitmap();
				getBitmapImageView();
				saveImageInApp(mBitmap, edtUsername.getText().toString().trim());
				Log.e(TAG, "mBitmap: " + mBitmap);
			}
		}
		if (resultCode == RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				String imagepath = getPath(selectedImageUri);
				System.out.println("Image Path : " + imagepath);
				Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
				imgAvatar.setImageBitmap(bitmap);
				// imgAvatar.setImageURI(selectedImageUri);
				getBitmapImageView();
				saveImageInApp(mBitmap, edtUsername.getText().toString().trim());

			}
		}
	}

	/**
	 * get ImagePath of image was choose from device
	 * 
	 * @param uri
	 * @return
	 */
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	/**
	 * Check the device to make sure it has the Google Play Services APK. If it
	 * doesn't, display a dialog that allows users to download the APK from the
	 * Google Play Store or enable it in the device's system settings.
	 */
	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(mContext);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this, 9000)
						.show();
			} else {
				Log.i(TAG, "This device is not supported.");
				finish();
			}
			return false;
		}
		return true;
	}

	/**
	 * class prepare to login twitter
	 * 
	 * @author MUI
	 * 
	 */
	private class TokenGet extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progress = new ProgressDialog(mContext);
			progress.setMessage("Loading Twitter ...");
			progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progress.setIndeterminate(true);
			progress.show();
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				requestToken = twitter.getOAuthRequestToken();
				oauth_url = requestToken.getAuthorizationURL();
			} catch (TwitterException e) {
				e.printStackTrace();
			}
			return oauth_url;

		}

		@SuppressLint("SetJavaScriptEnabled")
		@SuppressWarnings("null")
		@Override
		protected void onPostExecute(String oauth_url) {
			super.onPostExecute(oauth_url);
			if (oauth_url != null) {
				progress.hide();
				Log.e("URL", "oauth _url: " + oauth_url);
				auth_twitter_dialog = new Dialog(mContext);
				auth_twitter_dialog
						.requestWindowFeature(Window.FEATURE_NO_TITLE);

				auth_twitter_dialog
						.setContentView(R.layout.auth_twitter_dialog);
				web = (WebView) auth_twitter_dialog.findViewById(R.id.webv);
				web.getSettings().setJavaScriptEnabled(true);
				web.loadUrl(oauth_url);
				web.setWebViewClient(new WebViewClient() {
					boolean authComplete = false;

					@Override
					public void onPageStarted(WebView view, String url,
							Bitmap favicon) {
						super.onPageStarted(view, url, favicon);
					}

					@Override
					public void onPageFinished(WebView view, String url) {
						super.onPageFinished(view, url);

						if (url.contains("oauth_verifier")
								&& authComplete == false) {
							authComplete = true;
							Log.e("Url onPageFinished ", "url onPageFinished: "
									+ url);
							Uri uri = Uri.parse(url);
							oauth_verifier = uri
									.getQueryParameter("oauth_verifier");

							auth_twitter_dialog.dismiss();
							new AccessTokenGet().execute();
						} else if (url.contains("dennied")) {
							auth_twitter_dialog.dismiss();
							Toast.makeText(mContext,
									"Sorry !, Permission Denied",
									Toast.LENGTH_SHORT).show();
						}
					}
				});
				auth_twitter_dialog.show();
				auth_twitter_dialog.setCancelable(true);

			} else {
				Toast.makeText(mContext,
						"Sorry !, Network Error or Invalid Credentials",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	/**
	 * AsyncTask class login twitter and get info user
	 * 
	 * @author MUI
	 * 
	 */
	private class AccessTokenGet extends AsyncTask<String, String, Boolean> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progress = new ProgressDialog(mContext);
			progress.setMessage("Fetching Data ...");
			progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progress.setIndeterminate(true);
			progress.show();
		}

		@Override
		protected Boolean doInBackground(String... params) {
			try {
				if (accessToken == null) {
					accessToken = twitter.getOAuthAccessToken(requestToken,
							oauth_verifier);
				}
				User user = twitter.showUser(accessToken.getUserId());
				mUsername = user.getName();
				mAvatarUrl = user.getOriginalProfileImageURL();

				Log.i(TAG, "username: " + user.getName());
				return true;

			} catch (TwitterException e) {
				e.printStackTrace();
				return false;
			}

		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (result) {
				progress.dismiss();
				edtUsername.setText(mUsername);
				DownloadImage dowloadImage = new DownloadImage(mContext,
						imgAvatar);
				dowloadImage.execute(mAvatarUrl);
				// mBitmap = dowloadImage.getBitmap();
				getBitmapImageView();
				Log.e(TAG, "mBitmap: " + mBitmap);
				saveImageInApp(mBitmap, edtUsername.getText().toString().trim());
			}
		}

	}
}
